//
//  RootViewController.m
//  miaopai
//
//  Created by Crow Zhang on 15/11/12.
//  Copyright © 2015年 Crow Zhang. All rights reserved.
//

#import "RootViewController.h"
#import "ClearViewController.h"
#import "CustomerTabBarButton.h"
#import "MyVideo.h"
#import "CoreData.h"
#import <ALBBQuPaiPlugin/ALBBQuPaiPluginPluginServiceProtocol.h>
#import <TAESDK/TaeSDK.h>


@interface RootViewController ()<ClearViewControllerDelegate>

@property(retain,nonatomic) UIView *tabbarView;//自定义个底部的tabbar视图

@property(retain, nonatomic)CustomerTabBarButton *homeButton;

@property(nonatomic, retain)CustomerTabBarButton *hotButton;

@property(nonatomic, retain)UIButton *moreButton;

@property(nonatomic, retain)CustomerTabBarButton *topicButton;

@property(nonatomic, retain)CustomerTabBarButton *myselfButton;

@property(nonatomic, retain)UINavigationController *navigation;

@end

@implementation RootViewController

{
    BOOL _down;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self configTabbarView];
}

- (void)dealloc
{
    [_tabbarView release];
    [_homeButton release];
    [_hotButton release];
    [_moreButton release];
    [_topicButton release];
    [_myselfButton release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 点击自定义的那个tabbar视图上的按钮
-(void)tapButton:(UIButton *)button
{
    
    if (button.tag - 1000==2)//点击加号按钮
    {
        
    }
    
    else if(button.tag - 1000 >=3) //因为有5个按钮,现在只有4个ViewController,selectedIndex会向前移动一个
    {
        [self setSelectedIndex:button.tag - 1000 - 1];
    }
    
    else
    {
        [self setSelectedIndex:button.tag - 1000]; //给tabbar设置选中的ViewController
    }
    
}

#pragma mark - 配置tabbarView
- (void)configTabbarView
{
    self.tabBar.hidden=YES;//隐藏掉系统的bar
    UIScreen *s=[UIScreen mainScreen];
    CGFloat wid=[s bounds].size.width;
    CGFloat height=[s bounds].size.height;
    
    self.tabbarView = [[UIView alloc]initWithFrame:CGRectMake(0, height-48, wid, 48)];
    self.tabbarView.backgroundColor=[UIColor colorWithRed:1 green:1 blue:1 alpha:0.0];
    self.tabbarView.layer.shadowOffset = CGSizeMake(0, -0.1);
    self.tabbarView.layer.shadowColor = [[UIColor grayColor] CGColor];
    self.tabbarView.layer.shadowOpacity = 0.8;
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
    effectView.frame = self.view.frame;
    [self.tabbarView addSubview:effectView];
    [effectView release];
    [self.view addSubview:self.tabbarView];//自定的tabbar
    [self.tabbarView release];
    
    self.homeButton =[[CustomerTabBarButton alloc] initWithFrame:CGRectMake(0 , 0, wid/5.0, 48)];
    self.homeButton.image.image = [UIImage imageNamed:@"iconfont-zhuye-2"];
    self.homeButton.textLabel.text = @"首页";
    [self.homeButton addMyTarget:self action:@selector(homeButtonAction:)];
    [self.tabbarView addSubview:self.homeButton];
    [self.homeButton release];
    
    self.hotButton = [[CustomerTabBarButton alloc] initWithFrame:CGRectMake(1 * wid/5.0, 0, wid/5.0, 48)];
    self.hotButton.image.image = [UIImage imageNamed:@"iconfont-bangdan"];
    self.hotButton.textLabel.text = @"热榜";
    [self.hotButton addMyTarget:self action:@selector(hotButtonAction:)];
    [self.tabbarView addSubview:self.hotButton];
    [self.hotButton release];
    
    self.topicButton =[[CustomerTabBarButton alloc] initWithFrame:CGRectMake(3 * wid/5.0 , 0, wid/5.0, 48)];
    self.topicButton.image.image = [UIImage imageNamed:@"iconfont-icon42-2"];
    self.topicButton.textLabel.text = @"话题";
    [self.topicButton addMyTarget:self action:@selector(topicButtonAction:)];
    [self.tabbarView addSubview:self.topicButton];
    [self.topicButton release];
    
    self.myselfButton = [[CustomerTabBarButton alloc] initWithFrame:CGRectMake(4 * wid/5.0, 0, wid/5.0, 48)];
    self.myselfButton.image.image = [UIImage imageNamed:@"iconfont-wode"];
    self.myselfButton.textLabel.text = @"我的";
    [self.myselfButton addMyTarget:self action:@selector(myselfButtonAction:)];
    [self.tabbarView addSubview:self.myselfButton];
    [self.tabbarView release];
    
    self.moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.moreButton.frame=CGRectMake(2*wid/5.0, - 10, wid/5.0, 58);
    [self.moreButton setBackgroundColor:[UIColor colorWithRed:0.945 green:0.914 blue:0.129 alpha:1.000]];
    self.moreButton.layer.cornerRadius = 8;
    [self.moreButton setImage:[UIImage imageNamed:@"iconfont-plus-2"] forState:UIControlStateNormal];
    [self.moreButton setImage:[UIImage imageNamed:@"iconfont-plus-2"] forState:UIControlStateHighlighted];
    [self.moreButton setImageEdgeInsets:UIEdgeInsetsMake(10, wid/5.0 / 2- 19, 10, wid/5.0 / 2 - 19)];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(btnLong:)];
    longPress.minimumPressDuration = 0.7; //定义按的时间
    [self.moreButton addGestureRecognizer:longPress];
    [longPress release];
    [self.moreButton addTarget:self action:@selector(moreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.tabbarView addSubview:self.moreButton];
    
}

- (void)homeButtonAction:(CustomerTabBarButton *)sender
{
    [self setSelectedIndex:0];
    self.homeButton.image.image = [UIImage imageNamed:@"iconfont-zhuye-2"];
    self.hotButton.image.image = [UIImage imageNamed:@"iconfont-bangdan"];
    self.topicButton.image.image = [UIImage imageNamed:@"iconfont-icon42-2"];
    self.myselfButton.image.image = [UIImage imageNamed:@"iconfont-wode"];
}

- (void)hotButtonAction:(CustomerTabBarButton *)sender
{
    [self setSelectedIndex:1];
    self.homeButton.image.image = [UIImage imageNamed:@"iconfont-zhuye-3"];
    self.hotButton.image.image = [UIImage imageNamed:@"iconfont-bangdan-2"];
    self.topicButton.image.image = [UIImage imageNamed:@"iconfont-icon42-2"];
    self.myselfButton.image.image = [UIImage imageNamed:@"iconfont-wode"];
}

- (void)topicButtonAction:(CustomerTabBarButton *)sender
{
    [self setSelectedIndex:2];
    self.homeButton.image.image = [UIImage imageNamed:@"iconfont-zhuye-3"];
    self.hotButton.image.image = [UIImage imageNamed:@"iconfont-bangdan"];
    self.topicButton.image.image = [UIImage imageNamed:@"iconfont-icon42"];
    self.myselfButton.image.image = [UIImage imageNamed:@"iconfont-wode"];
}

- (void)myselfButtonAction:(CustomerTabBarButton *)sender
{
    [self setSelectedIndex:3];
    self.homeButton.image.image = [UIImage imageNamed:@"iconfont-zhuye-3"];
    self.hotButton.image.image = [UIImage imageNamed:@"iconfont-bangdan"];
    self.topicButton.image.image = [UIImage imageNamed:@"iconfont-icon42-2"];
    self.myselfButton.image.image = [UIImage imageNamed:@"iconfont-wode-2"];
}

- (void)moreButtonAction:(UIButton *)sender
{
    ClearViewController *clearView = [[ClearViewController alloc] init];
    clearView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    clearView.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    clearView.delegate = self;
    [self presentViewController:clearView animated:YES completion:nil];
    [clearView release];
}

- (void)btnLong:(UIButton *)sender
{
    NSLog(@"录制视频");
//    QPRecordParamViewController *record = [[QPRecordParamViewController alloc] initWithNibName:@"QPRecordParamViewController" bundle:nil];
//    [self presentViewController:record animated:YES completion:nil];
    [self recodeMyVideo];
}

- (void)toView:(UINavigationController *)view
{
    [self presentViewController:view animated:YES completion:nil];
}

- (void)recodeMyVideo
{
    id<ALBBQuPaiPluginPluginServiceProtocol> sdk = [[TaeSDK sharedInstance] getService:@protocol(ALBBQuPaiPluginPluginServiceProtocol)];
    [sdk setDelegte:(id<QupaiSDKDelegate>)self];
    
    
    //    UIViewController *recordController = [sdk createRecordViewControllerWithMaxDuration:[_durationTextField.text integerValue]
    //                                                                                              bitRate:[_bitRateTextField.text integerValue]
    //                                                                          thumbnailCompressionQuality:[_qualityThumbnail.text floatValue]
    //                                                                                       watermarkImage:_enableWaterMask.on ? [UIImage imageNamed:@"watermask"] : nil watermarkPosition:QupaiSDKWatermarkPositionTopRight
    //                                                                                      enableMoreMusic:_enableMoreMusic.on
    //                                                                                         enableImport:_enableImportSwitch.on];
    
    
    
    //    UIViewController *recordController = [sdk createRecordViewControllerWithMaxDuration:[_durationTextField.text integerValue]
    //                                                                                bitRate:[_bitRateTextField.text integerValue]
    //                                                            thumbnailCompressionQuality:[_qualityThumbnail.text floatValue]
    //                                                                         watermarkImage:_enableWaterMask.on ? [UIImage imageNamed:@"watermask"] : nil watermarkPosition:QupaiSDKWatermarkPositionTopRight
    //                                                                        enableMoreMusic:_enableMoreMusic.on
    //                                                                           enableImport:_enableImportSwitch.on
    //                                                                      enableVideoEffect:_enableVideoEffect.on];
    
    
    
    UIViewController *recordController = [sdk createRecordViewControllerWithMaxDuration:8
                                                                                bitRate:2000000
                                                            thumbnailCompressionQuality:0.3
                                                                         watermarkImage:nil
                                                                      watermarkPosition:QupaiSDKWatermarkPositionTopRight
                                                                              tintColor:[UIColor colorWithRed:125/255.0 green:125/255.0 blue:125/255.0 alpha:1]
                                                                        enableMoreMusic:NO
                                                                           enableImport:NO
                                                                      enableVideoEffect:YES];
    
    
    self.navigation = [[UINavigationController alloc] initWithRootViewController:recordController];
    self.navigation.navigationBarHidden = YES;
    [self presentViewController:self.navigation animated:YES completion:nil];
    
}

- (void)qupaiSDK:(id<ALBBQuPaiPluginPluginServiceProtocol>)sdk compeleteVideoPath:(NSString *)videoPath thumbnailPath:(NSString *)thumbnailPath
{
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    [self dismissViewControllerAnimated:YES completion:nil];
    
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSDictionary *fileAttributes = [manager attributesOfItemAtPath:videoPath error:nil];
    NSNumber *fileSize = [fileAttributes objectForKey:NSFileSize];
    NSLog(@"File size: %qi\n", [fileSize unsignedLongLongValue]);
    if (fileSize) {
        CoreData *coreDataManager = [CoreData shareManagerWithFile:@"joke"];
        MyVideo *video = [NSEntityDescription insertNewObjectForEntityForName:@"MyVideo" inManagedObjectContext:coreDataManager.managedObjectContext];
        
        NSDate *  senddate=[NSDate date];
        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
        NSString *  locationString=[dateformatter stringFromDate:senddate];
        NSLog(@"%@",locationString);
        video.time = locationString;
        
        NSString *videoDocumentPath = [documentPath stringByAppendingPathComponent:@"video"];
        [manager createDirectoryAtPath:videoDocumentPath withIntermediateDirectories:YES attributes:nil error:nil];
        NSString *picDocumentPath = [documentPath stringByAppendingPathComponent:@"pic"];
        [manager createDirectoryAtPath:picDocumentPath withIntermediateDirectories:YES attributes:nil error:nil];
        
        //NSLog(@"Qupai SDK compelete %@",videoPath);
                if (videoPath) {
            
            video.videoURL = [videoDocumentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4", locationString]];
            BOOL isMove = [manager moveItemAtPath:videoPath toPath:video.videoURL error:nil];
            NSLog(@"%d", isMove);
            UISaveVideoAtPathToSavedPhotosAlbum(video.videoURL, nil, nil, nil);
        }
        if (thumbnailPath) {
            //UIImageWriteToSavedPhotosAlbum([UIImage imageWithContentsOfFile:thumbnailPath], nil, nil, nil);
            video.picURL = [picDocumentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", locationString]];
            BOOL isMove = [manager moveItemAtPath:thumbnailPath toPath:video.picURL error:nil];
            NSLog(@"%d", isMove);
        }
        
        
        [coreDataManager saveContext];
    }
    
    
}

- (void)recodeVideo
{
    [self recodeMyVideo];
}

//- (NSArray *)qupaiSDKMusics:(id<ALBBQuPaiPluginPluginServiceProtocol>)sdk
//{
//    NSString *baseDir = [[NSBundle mainBundle] bundlePath];
//    NSString *configPath = [[NSBundle mainBundle] pathForResource:_down ? @"music2" : @"music1" ofType:@"json"];
//    NSData *configData = [NSData dataWithContentsOfFile:configPath];
//    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:configData options:NSJSONReadingAllowFragments error:nil];
//    NSArray *items = dic[@"music"];
//    
//    NSMutableArray *array = [NSMutableArray array];
//    for (NSDictionary *item in items) {
//        NSString *path = [baseDir stringByAppendingPathComponent:item[@"resourceUrl"]];
////        QPEffectMusic *effect = [[QPEffectMusic alloc] init];
////        effect.name = item[@"name"];
////        effect.eid = [item[@"id"] intValue];
////        effect.musicName = [path stringByAppendingPathComponent:@"audio.mp3"];
////        effect.icon = [path stringByAppendingPathComponent:@"icon.png"];
////        [array addObject:effect];
//    }
//    return array;
//}

//- (void)setHidesBottomBarWhenPushed:(BOOL)hidesBottomBarWhenPushed
//{
//    self.tabbarView.hidden = YES;
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
